import 'package:dio/dio.dart';
import 'package:flutter2/generated/json/base/json_convert_content.dart';
import 'package:flutter2/utils/log.dart';
import 'package:flutter2/utils/user.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:package_info_plus/package_info_plus.dart';

String? appssid;

int? userId;

resetId() {
  appssid = null;
  userId = null;
}

Map<String, dynamic> getParams() {
  Map<String, dynamic> map = {};
  map["easefar"] = "es";
  map["stewardessengland"] = "googleplay";
  map["untruebanana"] = appssid ?? "2357";
  map["evenwebsiteprinciple"] = userId ?? UserUtil.getUser().userId;
  return map;
}

Map<String, dynamic> getHeaders() {
  Map<String, dynamic> map = {};
  map["easefar"] = "es";
  map["anxiousbarber"] = "MX";
  map["spyappropriatecongratulation"] = "1";
  map["commitflamingidea"] = appssid ?? "2357";
  map["becomecushionchickchinese"] = UserUtil.getUser().token;
  map["motorbikechalkexplicit"] = userId ?? UserUtil.getUser().userId;
  return map;
}

class DioManager {
  DioManager._();

  static final Dio _dio = Dio(
    BaseOptions(
      baseUrl: "http://94.74.106.175/lemocrecredito/",
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
    ),
  );

  static request<T>({
    required String path,
    Map<String, dynamic>? data,
    Function(T? data)? onSuccess,
    bool Function(Exception e)? onError,
    Function()? onFinish,
    bool showLoading = true,
    bool autoDismiss = true,
  }) async {
    http(
      onLoading: () async {
        T? t = await requestAwait(path: path, data: data);
        onSuccess?.call(t);
      },
      onError: onError,
      onFinish: onFinish,
      showLoading: showLoading,
      autoDismiss: autoDismiss,
    );
  }

  static Future<T?> requestAwait<T>({
    required String path,
    Map<String, dynamic>? data,
  }) async {
    T? t;
    data = data ?? getParams();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    data["rosenose"] = packageInfo.version;
    data["cheerfulplainburglar"] = packageInfo.buildNumber;
    LogUtils.log(data);
    final response = await _dio.request<Map<String, dynamic>>(
      path,
      data: FormData.fromMap(data),
      options: Options(
        method: "post",
        headers: getHeaders(),
      ),
    );
    if (response.statusCode != 200) {
      throw Exception(response.statusMessage);
    }
    if (response.data?.isEmpty != false) {
      throw Exception("response data isEmpty");
    }
    Map<String, dynamic> map = response.data!;
    if (map["benefitsailorsuspect"] == 1000) {
      LogUtils.log(map["rowinfluencedecision"]);
      t = JsonConvert.fromJsonAsT<T>(map["rowinfluencedecision"]);
    } else {
      throw MyException(map["ambulanceusual"]);
    }
    return t;
  }

  static http({
    required Function() onLoading,
    bool Function(Exception e)? onError,
    Function()? onFinish,
    bool showLoading = true,
    bool autoDismiss = true,
  }) async {
    try {
      if (showLoading && !EasyLoading.isShow) {
        EasyLoading.show(maskType: EasyLoadingMaskType.clear);
      }
      await onLoading();
      if (autoDismiss) EasyLoading.dismiss(animation: false);
    } on Exception catch (e) {
      EasyLoading.dismiss(animation: false);
      bool toast = onError?.call(e) ?? true;
      if (toast) {
        SmartDialog.showToast(handlerException(e));
      }
    } finally {
      onFinish?.call();
    }
  }
}

String handlerException(Exception e) {
  String msg = "";
  if (e is DioException) {
    msg = "网络不佳，请稍后再试";
  } else if (e is MyException) {
    msg = e.message;
  }
  if (msg.isEmpty) {
    msg = "未知错误";
  }
  LogUtils.log(msg);
  return msg;
}

class MyException implements Exception {
  String message = "";

  MyException(this.message);
}
